use std::any::{Any, TypeId};
use std::sync::mpsc;
use std::thread::sleep;
use std::time::Duration;
use log::info;
use tokio::sync::oneshot;
use rpc::{send, spawn};

#[test]
fn mpsc_test() {
    let (tx, rx) = mpsc::channel::<Box<dyn Any + Send>>(/* usize */);

    // 发送不同类型的数据
    tx.send(Box::new(42_i32)).unwrap();
    tx.send(Box::new("hello".to_string())).unwrap();
    tx.send(Box::new(vec![1, 2, 3])).unwrap();

    drop(tx);
    // 接收并向下转换
    while let Ok(any_box) = rx.recv() {
        // match any_box.downcast::<i32>() {
        //     Ok(num) => info!("i32: {}", num),
        //     Err(typed_any) => match typed_any.downcast::<String>() {
        //         Ok(s) => info!("String: {}", s),
        //         Err(_) => info!("Unknown type"),
        //     },
        // }
        if any_box.is::<i32>() {
            info!("i32: {}", any_box.downcast::<i32>().unwrap());
        } else if any_box.is::<String>() {
            info!("String: {}", any_box.downcast::<String>().unwrap());
        } else {
            info!("unknown box type");
        }
    }
}



struct TypedAny {
    type_id: TypeId,
    data: Box<dyn Any + Send>,
}

impl TypedAny {
    fn new<T: Any + Send>(data: T) -> Self {
        Self {
            type_id: TypeId::of::<T>(),
            data: Box::new(data),
        }
    }

    fn downcast<T: Any>(self) -> Result<Box<T>, Self> {
        if self.type_id == TypeId::of::<T>() {
            Ok(self.data.downcast::<T>().unwrap())
        } else {
            Err(self)
        }
    }
}

#[test]
fn test2() {
    let (tx, rx) = mpsc::channel::<TypedAny>();

    tx.send(TypedAny::new(42_i32)).unwrap();
    tx.send(TypedAny::new("hello".to_string())).unwrap();
    drop(tx);

    while let Ok(typed_any) = rx.recv() {
        match typed_any.downcast::<i32>() {
            Ok(num) => info!("i32: {}", num),
            Err(typed_any) => match typed_any.downcast::<String>() {
                Ok(s) => info!("String: {}", s),
                Err(_) => info!("Unknown type"),
            },
        }
    }
}

#[test]
fn oneshot_test() {
    let (tx, rx) = oneshot::channel::<Vec<u8>>();
}

#[tokio::test]
async fn mpsc2_test() {
    let (sender, mut receiver) = tokio::sync::mpsc::unbounded_channel::<i32>();
    let (oneshot_sender, oneshot_receiver) = tokio::sync::oneshot::channel::<bool>();

    tokio::spawn(async move {
        let mut i = 0;
        loop {
            i = i+1;
            if !send(&sender, i) {
                info!("send failed");
            }
            info!("send success, {}", i);
            sleep(Duration::from_millis(100));
            if i > 100 {
                oneshot_sender.send(true).unwrap();
                break;
            }
        }
    });

    tokio::spawn(async move {
        loop {
            let result = receiver.recv().await;
            match result {
                None => {
                    break;
                }
                Some(result) => {
                    info!("recv result: {:?}", result);
                }
            }
        }
    });

    oneshot_receiver.await.unwrap();
}